package com.familytree.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.familytree.common.exception.BusinessException;
import com.familytree.dto.MemberTreeDTO;
import com.familytree.model.Member;
import com.familytree.model.RelationType;
import com.familytree.model.Relationship;
import com.familytree.repository.MemberRepository;
import com.familytree.repository.RelationshipRepository;
import com.familytree.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;

@Service
@RequiredArgsConstructor
public class MemberServiceImpl implements MemberService {

    private final MemberRepository memberRepository;
    private final RelationshipRepository relationshipRepository;

    @Override
    public org.springframework.data.domain.Page<Member> findAll(String search, Pageable pageable) {
        Page<Member> page = new Page<>(pageable.getPageNumber() + 1, pageable.getPageSize());
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        if (search != null && !search.isEmpty()) {
            wrapper.like(Member::getName, search);
        }
        memberRepository.selectPage(page, wrapper);
        return new org.springframework.data.domain.PageImpl<>(page.getRecords(), pageable, page.getTotal());
    }

    @Override
    public Member findById(Long id) {
        Member member = memberRepository.selectById(id);
        if (member == null) {
            throw new BusinessException("成员不存在");
        }
        return member;
    }

    @Override
    public List<Member> search(String query, String type) {
        if ("name".equals(type)) {
            return memberRepository.searchByQuery(query);
        } else if ("date".equals(type)) {
            try {
                return memberRepository.searchByQuery(query);
            } catch (NumberFormatException e) {
                throw new BusinessException("日期格式不正确");
            }
        }
        throw new BusinessException("不支持的搜索类型");
    }

    @Override
    @Transactional
    public Member create(Member member) {
        member.setCreateDate(LocalDate.now());
        member.setUpdateDate(LocalDate.now());
        memberRepository.insert(member);
        return member;
    }

    @Override
    @Transactional
    public Member update(Long id, Member member) {
        Member existingMember = findById(id);
        member.setId(id);
        member.setUpdateDate(LocalDate.now());
        memberRepository.updateById(member);
        return member;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        Member member = findById(id);
        List<Relationship> relationships = relationshipRepository.findByMemberId(id);
        for (Relationship relationship : relationships) {
            relationshipRepository.deleteById(relationship.getId());
        }
        memberRepository.deleteById(id);
    }

    @Override
    @Transactional
    public Member addSpouse(Long memberId, Long spouseId, String marriageDate) {
        Member member = findById(memberId);
        Member spouse = findById(spouseId);

        Relationship existingSpouse = relationshipRepository.findSpouseRelationship(memberId);
        if (existingSpouse != null) {
            throw new BusinessException("该成员已有配偶");
        }

        Relationship relationship = new Relationship();
        relationship.setMemberId(memberId);
        relationship.setRelatedMemberId(spouseId);
        relationship.setRelationshipType(RelationType.SPOUSE.name());
        relationship.setMarriageDate(LocalDate.parse(marriageDate));
        relationship.setCreateDate(LocalDate.now());
        relationship.setUpdateDate(LocalDate.now());
        relationshipRepository.insert(relationship);

        return member;
    }

    @Override
    @Transactional
    public void deleteSpouse(Long memberId) {
        Relationship spouseRelationship = relationshipRepository.findSpouseRelationship(memberId);
        if (spouseRelationship == null) {
            throw new BusinessException("配偶关系不存在");
        }
        relationshipRepository.deleteById(spouseRelationship.getId());
    }

    @Override
    @Transactional
    public Member addChild(Long parentId, Long childId) {
        Member parent = findById(parentId);
        Member child = findById(childId);

        Relationship existingParent = relationshipRepository.findParentRelationship(childId);
        if (existingParent != null) {
            throw new BusinessException("该成员已有父母");
        }

        Relationship relationship = new Relationship();
        relationship.setMemberId(parentId);
        relationship.setRelatedMemberId(childId);
        relationship.setRelationshipType(RelationType.PARENT_CHILD.getName());
        relationship.setCreateDate(LocalDate.now());
        relationship.setUpdateDate(LocalDate.now());
        relationshipRepository.insert(relationship);

        return parent;
    }

    @Override
    public Map<String, Object> getFamilyTree(Long memberId) {
        Member member = findById(memberId);
        return buildFamilyTreeNode(member);
    }

    private Map<String, Object> buildFamilyTreeNode(Member member) {
        Map<String, Object> node = new HashMap<>();
        node.put("id", member.getId());
        node.put("name", member.getName());
        node.put("gender", member.getGender());
        node.put("birthDate", member.getBirthDate());
        node.put("deathDate", member.getDeathDate());
        node.put("role", member.getRole());
        node.put("avatarUrl", member.getAvatarUrl());

        // 获取配偶
        Member spouse = memberRepository.findSpouseByMemberId(member.getId());
        if (spouse != null) {
            node.put("spouse", buildFamilyTreeNode(spouse));
        }

        // 获取子女
        List<Member> children = memberRepository.findChildrenByParentId(member.getId());
        if (!children.isEmpty()) {
            List<Map<String, Object>> childrenNodes = new ArrayList<>();
            for (Member child : children) {
                childrenNodes.add(buildFamilyTreeNode(child));
            }
            node.put("children", childrenNodes);
        }

        return node;
    }

    @Override
    public MemberTreeDTO getFamilyTree() {
        // 获取家族创始人（role为"创始人"的成员）
        Member founder = memberRepository.findByRole("创始人");
        if (founder == null) {
            return null;
        }
        
        return buildFamilyTree(founder);
    }

    private MemberTreeDTO buildFamilyTree(Member member) {
        MemberTreeDTO dto = MemberTreeDTO.fromMember(member);
        
        // 获取配偶
        List<Relationship> spouseRelations = relationshipRepository.findByMember1IdAndType(
            member.getId(), RelationType.SPOUSE.getName());
        if (!spouseRelations.isEmpty()) {
            Relationship spouseRelation = spouseRelations.get(0);
            Member spouse = memberRepository.findById(spouseRelation.getRelatedMemberId()).orElse(null);
            spouse.setMarriageDate(spouseRelation.getMarriageDate());
            if (spouse != null) {
                dto.setSpouse(MemberTreeDTO.fromMember(spouse));
            }
        }
        
        // 获取子女
        List<Relationship> childRelations = relationshipRepository.findByMember1IdAndType(
            member.getId(), RelationType.PARENT_CHILD.getName());
        if (!childRelations.isEmpty()) {
            List<MemberTreeDTO> children = new ArrayList<>();
            for (Relationship childRelation : childRelations) {
                Member child = memberRepository.findById(childRelation.getRelatedMemberId()).orElse(null);
                if (child != null) {
                    children.add(buildFamilyTree(child));  // 递归构建子树
                }
            }
            dto.setChildren(children);
        }
        
        return dto;
    }
} 